package com.example.demosecurity.common.security;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class CustomAuthorizationFilter extends OncePerRequestFilter {
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public StringRedisTemplate stringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        return this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String res = stringRedisTemplate.opsForValue().get("ms:user:token:admin");
        if (res == null) {
            filterChain.doFilter(request, response);
            return;
        }
        JSONObject jsonObject = Objects.requireNonNull(JSON.parseObject(res));
        List<GrantedAuthority> roleList = new ArrayList<>();
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority(jsonObject.getString("role"));
        roleList.add(authority);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(res, jsonObject.getString("password"),roleList);
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request, response);
    }
}
